// 创建画布
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

// 加载图片,通过创建简单的图片对象来实现加载
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
    bgReady = true;
}
bgImage.src = "images/background.png";
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
    heroReady = true;
}
heroImage.src = "images/hero.png";
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
    monsterReady = true;
}
monsterImage.src = "images/monster.png";

// 定义游戏对象
var hero = {
    speed:256,
};
var monster = {};
var monstersCaught = 0;  // 用来存储怪物被捉住的次数

// 处理用户的输入
var keysDown = {};  // 用keysDown这个对象来保存用户按下的键值
addEventListener(
    "keydown",
    function(e) {
        keysDown[e.keyCode] = true;
    },
    false
);
addEventListener(
    "keyup",
    function(e) {
        delete keysDown[e.keyCode];
    },
    false
);

// 游戏结束时开始新一轮的游戏，将英雄放于画布中心，怪物放于随机某处
// hero图片大小为32*32，monster图片大小为30*32
var reset = function () {
    hero.x = canvas.width / 2;
    hero.y=canvas.height / 2;
    monster.x = 32 + Math.random() * (canvas.width - 64);
    monster.y = 32 + Math.random() * (canvas.height - 64);
}

// 更新游戏对象
var update = function (modifier) {
    // 37,38,39,40上下左右键
    if(38 in keysDown){
        hero.y -= hero.speed * modifier;
    }
    if(40 in keysDown){
        hero.y += hero.speed * modifier; 
    }
    if(37 in keysDown){
        hero.x -=hero.speed * modifier;
    }
    if(39 in keysDown){
        hero.x += hero.speed * modifier;
    }
    // 判断敌人是否被抓
    if(hero.x <= monster.x + 32 && monster.x <= hero.x + 32
        && hero.y <= monster.y + 32 && monster.y <= hero.y + 32 )
    {
        ++monstersCaught;
        reset();
    }
}

// 渲染物体 背景，敌人，英雄
var render = function () {
    if(bgReady){
        ctx.drawImage(bgImage,0,0);
    }
    if(heroReady){
        ctx.drawImage(heroImage,hero.x,hero.y);
    }
    if(monsterReady){
        ctx.drawImage(monsterImage,monster.x,monster.y);
    }
    // 计分部分
    // 改变Canvas的绘图上下文的样式并调用fillText来绘制文字
    ctx.fillStyle = "rgb(250,250,250)";  //定义画布颜色
    ctx.font = "24px Helvetica"; //画布上文字的字体及大小
    ctx.textAlign = "left";  //相对于某条竖直基线后的对齐方式 可以为start end left right start表示基线在文字开头...
    ctx.textBaseline = "top"; //相对于某条水平基线后的对齐方式，Top Bottom Middle Alphabetic Hanging
    ctx.fillText("Goblins caught:" + monstersCaught,32,32);
}

// 主循环函数 游戏的循环结构
var main = function () {
    var now = Date.now();
    var delta = now - then;
    update(delta / 1000);
    render();
    then = now;
    requestAnimationFrame(main);
}

// 设置requestAnimationFrame() 解决浏览器兼容问题
var w = window;
requestAnimationFrame = w.requestAnimationFrame ||
    w.webkitRequestAnimationFrame ||
    w.msRequestAnimationFrame ||
    w.mozRequestAnimationFrame;

// 调用相应的函数启动游戏
var then = Date.now();
reset();
main();